<template>
	<view class="page-container">
		<view class="nickName-container">
			<view class="nickName-label">昵称</view>
			<input type="text" placeholder="请输入昵称" v-model="nickname" maxlength="15" class="nickName-input-container">
		</view>

		<view class="save-nickName" @click="updateNickname">
			保存
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue';
	import { onShow } from "@dcloudio/uni-app";
	import { apiUpdateNickname } from '@/api/user';
	import { useShowToast } from '../../utils/tools';
	const nickname = ref("");
	/**
	 * 从缓存更新最新的用户信息
	 */
	const updateNickNameByStorage = () => {
		const storageInfo = uni.getStorageSync('userInfo');
		nickname.value = storageInfo.nickname;
	}
	onShow(() => {
		updateNickNameByStorage();
	})

	/**
	 * 更新用户昵称
	 */
	const updateNickname = async () => {
		try {
			uni.showLoading({
				title: '保存中'
			})
			await apiUpdateNickname(nickname.value);
			const storageInfo = uni.getStorageSync('userInfo');
			storageInfo.nickname = nickname.value;
			console.log(storageInfo);
			uni.setStorageSync("userInfo", storageInfo);
			uni.hideLoading()
			useShowToast('修改成功', 'success', true);
			setTimeout(() => {
				uni.navigateBack()
			}, 2000)
		} catch (err) {
			uni.hideLoading()
			console.error(err);
			useShowToast('保存失败,请重试!')
		}
	}
</script>

<style lang="scss">
	.page-container {
		.nickName-container {
			width: 100%;
			padding: 0 48rpx;
			padding-top: 100rpx;
			display: flex;
			align-items: center;

			.nickName-label {
				padding-right: 24rpx;
			}

			.nickName-input-container {
				width: 574rpx;
				height: 64rpx;
				background: #2A2A2A;
				border-radius: 8rpx;
				padding: 0 24rpx;
				box-sizing: border-box;
			}
		}

		.save-nickName {
			width: 630rpx;
			height: 80rpx;
			background: #25DADA;
			border-radius: 40rpx;
			font-size: 32rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 80rpx;
			margin: auto;
			margin-top: 248rpx;

		}
	}
</style>